﻿using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.ComponentModel;
using System.Linq;
using CleanUpTool.Models;
using CleanUpTool.Views;

namespace CleanUpTool;

/// <summary>
/// 用于表示扫描结果项的数据模型
/// </summary>
public class CleanupItem : INotifyPropertyChanged
{
    private bool _isSelected;

    public string Type { get; set; } // 文件夹类型 (bin, obj, 等)
    public string Path { get; set; } // 完整路径
    public string Size { get; set; } // 格式化的大小
    public long SizeBytes { get; set; } // 原始字节大小

    public bool IsSelected
    {
        get => _isSelected;
        set
        {
            if (_isSelected != value)
            {
                _isSelected = value;
                OnPropertyChanged(nameof(IsSelected));
            }
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
    private ObservableCollection<CleanupItem> _cleanupItems;
    private string _selectedFolderPath;
    private CleanupConfiguration _configuration;

    public MainWindow()
    {
        InitializeComponent();
        _cleanupItems = new ObservableCollection<CleanupItem>();
        lvResults.ItemsSource = _cleanupItems;
        btnCleanUp.IsEnabled = false;
        btnSelectAll.IsEnabled = false;
        
        // 加载配置
        _configuration = CleanupConfiguration.Load();
    }
    
    /// <summary>
    /// 窗口加载事件
    /// </summary>
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // 加载保存的目录到下拉列表
        RefreshSavedDirectories();
    }
    
    /// <summary>
    /// 刷新保存的目录列表
    /// </summary>
    private void RefreshSavedDirectories()
    {
        cmbSavedDirectories.ItemsSource = null;
        cmbSavedDirectories.ItemsSource = _configuration.SavedDirectories.Where(d => d.IsEnabled);
        
        if (cmbSavedDirectories.Items.Count > 0)
        {
            cmbSavedDirectories.SelectedIndex = 0;
        }
    }
    
    /// <summary>
    /// 保存的目录选择变更事件
    /// </summary>
    private void cmbSavedDirectories_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var selectedDirectory = cmbSavedDirectories.SelectedItem as DirectoryConfig;
        if (selectedDirectory != null)
        {
            _selectedFolderPath = selectedDirectory.Path;
            txtFolderPath.Text = _selectedFolderPath;
            _cleanupItems.Clear();
            UpdateStats();
            
            // 如果配置了自动扫描，则立即扫描
            if (_configuration.AutoScanAfterSelect)
            {
                btnScan_Click(this, null);
            }
        }
    }
    
    /// <summary>
    /// 配置按钮点击事件
    /// </summary>
    private void btnConfig_Click(object sender, RoutedEventArgs e)
    {
        var configWindow = new ConfigurationWindow(_configuration);
        configWindow.Owner = this;
        
        if (configWindow.ShowDialog() == true)
        {
            // 刷新保存的目录列表
            RefreshSavedDirectories();
        }
    }

    /// <summary>
    /// 选择项目文件夹按钮点击事件
    /// </summary>
    private void btnSelectFolder_Click(object sender, RoutedEventArgs e)
    {
        var dialog = new System.Windows.Forms.FolderBrowserDialog
        {
            Description = "选择Visual Studio项目文件夹",
            UseDescriptionForTitle = true
        };

        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            _selectedFolderPath = dialog.SelectedPath;
            txtFolderPath.Text = _selectedFolderPath;
            _cleanupItems.Clear();
            UpdateStats();
            
            // 询问是否保存此目录
            var result = System.Windows.MessageBox.Show(
                "是否将此目录添加到保存的目录列表中？",
                "保存目录",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);
                
            if (result == MessageBoxResult.Yes)
            {
                string name = System.IO.Path.GetFileName(_selectedFolderPath);
                _configuration.AddDirectory(name, _selectedFolderPath);
                RefreshSavedDirectories();
            }
        }
    }

    /// <summary>
    /// 扫描按钮点击事件
    /// </summary>
    private void btnScan_Click(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(_selectedFolderPath) || !Directory.Exists(_selectedFolderPath))
        {
           System.Windows. MessageBox.Show("请先选择有效的项目文件夹", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }

        Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
        _cleanupItems.Clear();

        try
        {
            // 扫描bin和obj文件夹
            ScanDirectory(_selectedFolderPath);

            // 更新统计信息
            UpdateStats();

            // 启用按钮
            btnCleanUp.IsEnabled = _cleanupItems.Count > 0;
            btnSelectAll.IsEnabled = _cleanupItems.Count > 0;
        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show($"扫描过程中发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        finally
        {
            Mouse.OverrideCursor = null;
        }
    }

    /// <summary>
    /// 递归扫描目录查找bin和obj文件夹
    /// </summary>
    private void ScanDirectory(string directoryPath)
    {
        try
        {
            // 检查当前目录是否为bin或obj
            string dirName = new DirectoryInfo(directoryPath).Name.ToLower();
            if (dirName == "bin" || dirName == "obj")
            {
                // 计算文件夹大小
                long size = CalculateDirectorySize(directoryPath);
                string formattedSize = FormatSize(size);

                // 添加到列表
                _cleanupItems.Add(new CleanupItem
                {
                    Type = dirName,
                    Path = directoryPath,
                    Size = formattedSize,
                    SizeBytes = size,
                    IsSelected = true
                });

                return; // 不再递归扫描bin或obj内部
            }

            // 递归扫描子目录
            foreach (string subDir in Directory.GetDirectories(directoryPath))
            {
                ScanDirectory(subDir);
            }
        }
        catch (UnauthorizedAccessException)
        {
            // 忽略无权限访问的目录
        }
        catch (Exception ex)
        {
            // 记录错误但继续扫描
            System.Diagnostics.Debug.WriteLine($"扫描目录 {directoryPath} 时出错: {ex.Message}");
        }
    }

    /// <summary>
    /// 计算目录大小
    /// </summary>
    private long CalculateDirectorySize(string directoryPath)
    {
        long size = 0;

        try
        {
            // 计算所有文件大小
            foreach (string file in Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories))
            {
                try
                {
                    FileInfo fileInfo = new FileInfo(file);
                    size += fileInfo.Length;
                }
                catch
                {
                    // 忽略无法访问的文件
                }
            }
        }
        catch
        {
            // 忽略无法访问的目录
        }

        return size;
    }

    /// <summary>
    /// 格式化文件大小显示
    /// </summary>
    private string FormatSize(long bytes)
    {
        string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
        int counter = 0;
        decimal number = bytes;

        while (Math.Round(number / 1024) >= 1)
        {
            number /= 1024;
            counter++;
        }

        return $"{number:n2} {suffixes[counter]}";
    }

    /// <summary>
    /// 更新统计信息
    /// </summary>
    private void UpdateStats()
    {
        int totalItems = _cleanupItems.Count;
        long totalSize = _cleanupItems.Sum(item => item.SizeBytes);

        txtTotalItems.Text = $"{totalItems} 个项目";
        txtTotalSize.Text = FormatSize(totalSize);
    }

    /// <summary>
    /// 全选按钮点击事件
    /// </summary>
    private void btnSelectAll_Click(object sender, RoutedEventArgs e)
    {
        bool selectAll = _cleanupItems.Any(item => !item.IsSelected);

        foreach (var item in _cleanupItems)
        {
            item.IsSelected = selectAll;
        }

        // 更新按钮文本
        btnSelectAll.Content = selectAll ? "取消全选" : "全选";
    }

    /// <summary>
    /// 清理按钮点击事件
    /// </summary>
    private void btnCleanUp_Click(object sender, RoutedEventArgs e)
    {
        var selectedItems = _cleanupItems.Where(item => item.IsSelected).ToList();

        if (selectedItems.Count == 0)
        {
            System.Windows.MessageBox.Show("请先选择要清理的项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }

        // 如果配置了显示确认对话框，则显示确认对话框
        bool shouldProceed = true;
        if (_configuration.ShowConfirmationBeforeCleanup)
        {
            var result = System.Windows.MessageBox.Show(
                $"确定要删除选中的 {selectedItems.Count} 个文件夹吗？此操作不可恢复！",
                "确认清理",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning);
                
            shouldProceed = (result == MessageBoxResult.Yes);
        }
        
        if (!shouldProceed)
        {
            return;
        }

        Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
        int successCount = 0;
        int failCount = 0;

        try
        {
            foreach (var item in selectedItems)
            {
                try
                {
                    Directory.Delete(item.Path, true);
                    successCount++;
                }
                catch (Exception ex)
                {
                    failCount++;
                    System.Diagnostics.Debug.WriteLine($"删除目录 {item.Path} 时出错: {ex.Message}");
                }
            }

            // 从列表中移除已成功删除的项目
            for (int i = _cleanupItems.Count - 1; i >= 0; i--)
            {
                if (_cleanupItems[i].IsSelected && !Directory.Exists(_cleanupItems[i].Path))
                {
                    _cleanupItems.RemoveAt(i);
                }
            }

            // 更新统计信息
            UpdateStats();

            // 显示结果
            System.Windows.MessageBox.Show(
                $"清理完成！成功: {successCount} 个, 失败: {failCount} 个",
                "清理结果",
                MessageBoxButton.OK,
                failCount > 0 ? MessageBoxImage.Warning : MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show($"清理过程中发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        finally
        {
            Mouse.OverrideCursor = null;
            btnCleanUp.IsEnabled = _cleanupItems.Count > 0;
            btnSelectAll.IsEnabled = _cleanupItems.Count > 0;
        }
    }
}